var animated = $('[data-like]');

animated.each(function(index, item) {
    $item = $(item);

    if($item.data('like')) {
        $item.addClass('liked').removeClass('unliked');
    }
});

$('.like').on('click', function (e) {
    e.preventDefault();
    var $currentTarget = $(e.currentTarget);
    var $socialMediaLike = $currentTarget.parent();
    var $dataLike = $socialMediaLike.find('.like-total');
    var dataLikeTotal = parseInt($dataLike.text());
    var imageId = $currentTarget.closest('.module-blog').find('#imgId').text(); // 假设imgId在.module-blog中

    console.log('imageId-->>', imageId);

    $.ajax({
        type: 'POST',
        url: '/likeImage', // 替换成处理点赞的后端端点
        data: { imageId: imageId },
        success: function (response) {
            console.log('点赞成功');
            if (!$currentTarget.data('like')) {
                $currentTarget.addClass('liked').removeClass('unliked');
                $currentTarget.data('like', true);
                $dataLike.html(dataLikeTotal + 1);
            } else {
                $currentTarget.removeClass('liked').addClass('unliked');
                $currentTarget.data('like', false);
                $dataLike.html(dataLikeTotal - 1);
            }
        },
        error: function (error) {
            console.error('点赞操作错误', error);
        }
    });
});




function showComments() {
    document.querySelector('.comments-container').style.display = 'block';
}

function closeComments() {
    document.querySelector('.comments-container').style.display = 'none';
}

function fetchComments(imageId) {
    // 使用Ajax向后端发送POST请求
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 解析后端返回的JSON数据
            var commentsData = JSON.parse(xhr.responseText);
            // 更新评论框内容
            var commentsList = document.getElementById('comments-list');
            commentsList.innerHTML = renderComments(commentsData);
            showComments(); // 显示评论框
        }
    };

    // 发送POST请求，将图片ID包含在请求体中
    xhr.open('POST', '/getComments', true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

    // 将数据作为JSON字符串发送
    var requestData = { imageId: imageId };
    xhr.send(JSON.stringify(requestData));
}

function renderComments(commentsData) {
    // 根据数据生成HTML字符串
    var htmlString = '';
    commentsData.forEach(function (comment) {
        htmlString += '<div class="comment">';
        htmlString += '<span class="comment-username">' + comment.username + ':</span>';
        htmlString += '<span class="comment-text">' + comment.comment + '</span>';
        htmlString += '<button class="close-comment-btn" onclick="closeComments()">关闭</button>';
        htmlString += '</div>';
    });
    return htmlString;
}

function loadImages() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var imageData = JSON.parse(xhr.responseText);
            renderImages(imageData);
        }
    };

    // Make a GET request to your backend controller to fetch image data
    xhr.open('GET', '/getFeedInfo', true);
    xhr.send();
}

function renderImages(imageData) {
    var container = document.querySelector('.row');

    imageData.forEach(function (image) {
        var imageContainer = document.createElement('div');
        imageContainer.classList.add('container', 'col-4');

        imageContainer.innerHTML = `
          <div class="module-blog">
            <div class="module-blog-img">
              <img style="width: 450px;height: 500px" src="${image.imageUrl}">
            </div>
            <div class="module-blog-content">
              <h3 class="title" id="username">${image.username}</h3>
              <h3 id="type">Category: ${image.category}</h3>
              <p class="text" id="imgId">${image.imageId}</p>
              <div style="display: inline">
                <div class="social-media">
                  <div class="social-media-comment" onclick="fetchComments('${image.imageId}')">
                    <span>${image.commentCount}</span>
                    <span class="fa fa-comments"></span>
                  </div>
                  <div class="social-media-like">
                    <div class="social-media-like-wrapper">
                      <span class="like-total" data-like-total="${image.likeCount}">${image.likeCount}</span>
                      <span class="like fa fa-heart" data-like="false"></span>
                    </div>
                  </div>
                  <a href="#" onclick="redirectToReport('${image.imageId}')"><img src="static/img/report.png" style="width: 20px;height: 20px;"></a>
                </div>
              </div>
            </div>
          </div>
          <form action="#"  >
            <textarea name="comment" id="comment" cols="30" rows="10" placeholder="Write your comment..."></textarea>
            <br />
            <input type="submit" value="Comment" onclick="submitComment(${image.imageId})"/>
          </form>
        `;

        container.appendChild(imageContainer);
    });
}

function submitComment( imgId) {
    var commentTextarea = document.getElementById('comment');
    var commentText = commentTextarea.value.trim();

    // 检查评论是否非空
    if (commentText !== '') {
        // 获取当前图片的ID（示例中假设有一个全局变量存储了当前图片的ID）
        var imageId = imgId; // 替换为获取当前图片ID的逻辑

        // 构建评论对象
        var commentData = {
            imageId: imageId,
            comment: commentText
        };

        // 发送评论数据到后端
        sendCommentToBackend(commentData);
    }
}

function sendCommentToBackend(commentData) {
    // 使用Ajax向后端发送POST请求
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 处理后端返回的响应，如果需要的话
                console.log('评论提交成功');
            } else {
                console.error('评论提交失败');
            }
        }
    };

    xhr.open('POST', '/postComment', true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

    // 将评论数据作为JSON字符串发送
    xhr.send(JSON.stringify(commentData));
}

function redirectToReport(commentId) {
    // Navigate to the report page with the id parameter
    window.location.href = "/report?commentId=" + commentId;
}